/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewProject.java
 *
 * Created on Feb 3, 2011, 1:22:40 PM
 */

package WorkSpace;

import java.awt.Dimension;
import java.awt.Point;
import java.io.File;

/**
 *
 * @author leng
 */
public class NewProject extends javax.swing.JFrame {

    /**The coordinates of the top left corner to the parent window.*/
    protected Point __parentWindowCoordinates = null;
    /**The size of the parent window.*/
    protected Dimension __parentWindowSize = null;

    /**point to main window*/
    protected UserInterface.GUI __gui = null;

    /** Creates new form NewProject */
    public NewProject(UserInterface.GUI _gui, Point _parentWindowCoordinates, Dimension _parentWindowSize)
    {
        // get values of imported variables
        this.__gui = _gui;
        this.__parentWindowCoordinates = _parentWindowCoordinates;
        this.__parentWindowSize = _parentWindowSize;

        // components init by JAVA system
        initComponents();
        
        // set screen location of this dialong
        setFramePosition();

        // set extra attributes to components
        setComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel_info = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Create New Project");
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(238, 238, 239));
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(240, 240, 240));

        jLabel3.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        jLabel3.setText("New Project Name:");

        jLabel_info.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel_info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/markerror.png"))); // NOI18N
        jLabel_info.setText("New Project Name:");

        jButton1.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        jButton1.setText("OK");
        jButton1.setPreferredSize(new java.awt.Dimension(100, 24));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel_info)
                        .addContainerGap(489, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 10, Short.MAX_VALUE)
                .add(jLabel_info)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jPanel2.setBackground(new java.awt.Color(253, 253, 253));
        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));

        jLabel1.setFont(new java.awt.Font("Cambria", 1, 14));
        jLabel1.setText("Create a new project");

        jLabel2.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jLabel2.setText("<html>Please assign a name to this project. eHOST will create a directory under  <p>your current workspace using this name.</html>");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(158, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(9, 9, 9)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START);

        jPanel3.setBackground(new java.awt.Color(240, 240, 240));

        jButton2.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        jButton2.setText("Cancel");
        jButton2.setPreferredSize(new java.awt.Dimension(100, 24));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(517, Short.MAX_VALUE)
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel3, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents


    /**Set screen location of this dialog. It will be put on the middle of the
     * right work space.
     */
    private void setFramePosition()
    {

        int width = 617, height = 250;
        this.setSize(new Dimension(width, height));
        this.setPreferredSize(new Dimension(width, height));

        //##1## dialog called from the NAV pane, set this dialog in the middle
        // of right area

        if((__parentWindowSize==null)||(__parentWindowCoordinates==null))
        {
            System.out.println("error 1102031516:: fail to import jcomponents.");
            return;
        }


        int x1 = __parentWindowCoordinates.x + (int)( (__parentWindowSize.width  - width  )/2 );
        int y1 = __parentWindowCoordinates.y + (int)( (__parentWindowSize.height - height )/2 );
        this.setLocation(x1, y1);

        return;
        
    }

    
    /**set some components just after loading the dialog, and before display
     * it on screen;
     */
    private void setComponents()
    {
        // hide the infor label after loading the dialog
        this.jLabel_info.setVisible(false);
    }
    

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // after user clicked OK button, we need to varify the directory name
        // and create it if necessary;
        if(preCheck())
        {
            // close this dialog
            this.dispose();
        }
        else
        {
            return;
        }

        // create this project folder
        createNewProjectFolder(jTextField1.getText().trim());

        // update project list on NAV pane
        __gui.display_refreshNAV_WorkSpace();
}//GEN-LAST:event_jButton1ActionPerformed


    /**Create a project by the given folder name; User this folder name*/
    private void createNewProjectFolder(String foldername)
    {
        try{

            //##1##  make sure that the folder name is not be empty
            if((foldername==null)||(foldername.trim().length()<1))
            {
                System.out.println("error 1102041049:: folder name could not be empty!!!");
                return;
            }

            String workspace = env.Parameters.WorkSpace.WorkSpace_AbsolutelyPath;

            //##2##  create main folder of this new project
            String path = workspace + File.separator + foldername.trim() + File.separator;
            File newfolder = new File(path);
            if(!newfolder.mkdirs()){
                System.out.println("error 1102041106:: fail to create folder for the new project!");
                return;
            }

            //##3## create subfolder of corpus for this project
            String corpuspath = path + "corpus" + File.separator;
            File corpus = new File(corpuspath);
            if(!corpus.mkdirs()){
                System.out.println("error 1102041107:: fail to create 'corpus' folder under the new project!");
            }

            //##4## create subfolder of "saved" for this project
            String savedpath = path + "saved" + File.separator;
            File saved = new File(savedpath);
            if(!saved.mkdirs()){
                System.out.println("error 1102041108:: fail to create 'saved' folder under the new project!");
            }
                    

        }
        catch(Exception ex)
        {
            System.out.println("error 1102041050:: fail to create new project folder :["
                    + foldername
                    + "]\n"
                    + ex.toString() );
        }
    }


    /**Verify this new project name came from the text filed, and make sure
     * there is no any illegal char occurred.
     */
    private boolean preCheck()
    {
        String projectname = jTextField1.getText();

        //##1## if projectname is null or empty
        if((projectname==null)||(projectname.trim().length()<1))
        {
            this.jLabel_info.setText("Project name could not be empty!!!");
            this.jLabel_info.setVisible(true);
            commons.Tools.beep();
            return false;
        }


        //##2## check folder name for validity, symbols, such as '$' '&' could
        //      not appeared in the string
        char[] result = checkValidity(projectname);
        if(result!=null)
        {
            String msg = "Wrong characters found:";
            for(char c:result)
            {
                if (c != ' ')
                {
                    msg = msg + " \'" + String.valueOf(c)+ "\'";
                }
            }
            this.jLabel_info.setText(msg);
            this.jLabel_info.setVisible(true);
            commons.Tools.beep();
            return false;
        }


        //##3## if it exists and it's a file
        String msg = existAsFile(projectname.trim());
        if(msg!=null)
        {
            this.jLabel_info.setText(msg);
            this.jLabel_info.setVisible(true);
            commons.Tools.beep();
            return false;
        }
        
        
        
        
        

        return true;

    }


    /*
    private boolean exists(String foldername )
    {
        try{
            
            if(foldername==null)
            {
                System.out.println("error 1102040942:: this filename is NULL.");
                return false;
            }

            String workspacepath = env.Parameters.WorkSpace.WorkSpace_AbsolutelyPath;
            String path = workspacepath + File.separator + foldername.trim();
            System.out.println("path "+ path);

        }
        catch(Exception ex)
        {
            System.out.println("error 1102040933");
        }

        return false;
    }
     * */
    

    
    private String existAsFile(String foldername)
    {
        try{
            if(foldername==null)
            {
                System.out.println("error 1102040942:: this filename is NULL.");
                return "folder name could not be empty.";
            }

            String workspacepath = env.Parameters.WorkSpace.WorkSpace_AbsolutelyPath;
            String path = workspacepath + File.separator + foldername.trim();

            File file = new File(foldername.trim());

            if(file.exists())
            {
                if(file.isFile())
                    return "There already has a file named \""
                    + file.getName()
                    +"\" exists under your current workspace!!!";
                else
                    return "You already has a project called this name. ";
            }
            
            
        }catch(Exception ex){
            System.out.println("error 1102040001");            
        }

        return null;
    }

    
    /**Check each character of the folder name. */
    private char[] checkValidity(String foldername)
    {
        if((foldername==null)||(foldername.trim().length()<1))
            return null;

        int size = foldername.length();
        char[] to_return = foldername.toCharArray();
        for(int i=0;i<size; i++)
        {
            boolean flag = false;
            char thischar = foldername.charAt(i);
            if((thischar<='Z')&&(thischar>='A'))
                flag = true;
            else if((thischar<='z')&&(thischar>='a'))
                flag = true;
            else if((thischar<='9')&&(thischar>='0'))
                flag = true;
            else if(thischar=='-')
                flag = true;
            else if(thischar=='_')
                flag = true;
            else if(thischar=='.')
                flag = true;
            else if(thischar=='~')
                flag = true;

            if(flag)
            {
                to_return[i]=' ';
            }
        }

        boolean flag = false;
        for(int i=0;i<size; i++)
        {
            if(to_return[i] != ' ')
            {
                flag = true;
                break;
            }
        }

        if(flag)
            return to_return;
        else return null;
    }


    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed

    /**
    * @param args the command line arguments
    */
    /*
     public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewProject().setVisible(true);
            }
        });
    }
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel_info;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}
